#include "offlineMessageModel.hpp"
#include "db/db.h"
#include <muduo/base/Logging.h>
#include "mysql_conn_pool.hpp"

//存储用户的离线消息
void offlineMessageModel::insert(int userid,string msg){
    //组装sql语句
    char sql[1024]={0};
    sprintf(sql,"insert into offlinemessage values('%d','%s')",userid,msg.c_str());

    //从数据库连接池中获取连接对象，并且使用RAII机制
    MySQL* mysql = nullptr;
    mysql_connpool_RAII RAII(&mysql,mysql_connPool::getInstance());

    if(mysql!=nullptr){
        if(!mysql->update(sql)){
            LOG_INFO<<"UserID[ "<<userid<<"]: insert offlineMessage failed! ";
        }
    }
}

//删除用户的离线消息
void offlineMessageModel::remove(int userid){
    //组装sql语句
    char sql[1024]={0};
    sprintf(sql,"delete from offlinemessage where userid='%d'",userid);

    //从数据库连接池中获取连接对象，并且使用RAII机制
    MySQL* mysql = nullptr;
    mysql_connpool_RAII RAII(&mysql,mysql_connPool::getInstance());

    if(mysql!=nullptr){
        if(!mysql->update(sql)){
            LOG_INFO<<"UserID[ "<<userid<<"]: delete offlineMessage failed! ";
        }
    }

}

//查询指定用户的全部离线信息，返回一个数组
vector<string> offlineMessageModel::query(int userid){
    //组装sql语句
    char sql[1024]={0};
    sprintf(sql,"select message from offlinemessage where userid = '%d'",userid);

    vector<string> vec;
    //从数据库连接池中获取连接对象，并且使用RAII机制
    MySQL* mysql = nullptr;
    mysql_connpool_RAII RAII(&mysql,mysql_connPool::getInstance());

    if(mysql!=nullptr){
        MYSQL_RES* res=mysql->query(sql);
        if(res!=nullptr){
            //将每一条离线消息放入数组中
            MYSQL_ROW row;
            while((row = mysql_fetch_row(res))!=nullptr){
                vec.push_back(row[0]);
            }

            mysql_free_result(res);
            return vec;
        }
        mysql_free_result(res);
    }
    return vec;
}
